import { Context } from 'koa'
import { getListSer,getAllListSer, addSer, putSer, getDetailSer, delSer } from '@/business/service'
import { userType} from '@/types'
import {  IshebeiQueryType, IshebeiQuerySerType, Ishebei, IshebeiSer } from '@/types/equipment/shebei'
import errors from '@/app/err.type'
import { formatHumpLineTransfer } from '@/business/utils'
import { excelJsExport } from '@/business/utils/excel'
import {  excelBaseStyle } from '@/business/public/excelMap'
import ShebeiTable2 from '@/mysql/model/equipment/shebei.model'
import { Op } from 'sequelize'
const { uploadParamsErr, getListErr, sqlErr, delErr, exportExcelErr} = errors

// 获取列表
export const getListMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const { pageNum, pageSize, ...params } = ctx.query as unknown as IshebeiQueryType
    let newParams = { pageNum, pageSize } as IshebeiQuerySerType
    if(params.deptId) newParams.dept_id = { [Op.eq]: params.deptId  }
    if(params.groupName) newParams.group_name = { [Op.eq]: params.groupName  }
    if(params.deviceName) newParams.device_name = { [Op.eq]: params.deviceName  }
    if(params.deviceVersion) newParams.device_version = { [Op.eq]: params.deviceVersion  }
    
    const res = await getListSer<IshebeiQuerySerType>(ShebeiTable2, newParams)

    ctx.state.formatData = res
    await next()
  } catch (error) {
    console.error('查询列表失败', error)
    return ctx.app.emit('error', getListErr, ctx)
  }
}
// 获取所有列表
export const getAllListMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    
    const res = await getAllListSer(ShebeiTable2)

    ctx.state.formatData = res
    await next()
  } catch (error) {
    console.error('查询列表失败', error)
    return ctx.app.emit('error', getListErr, ctx)
  }
}
// 获取列表查询条件
export const getListParamMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    let params:any =  {}
    if (ctx.request.body) {
      params = JSON.parse(Object.keys(ctx.request.body)[0])
    }
    let newParams = {  } as IshebeiQuerySerType
    if(params.deptId) newParams.dept_id = { [Op.eq]: params.deptId  }
    if(params.groupName) newParams.group_name = { [Op.eq]: params.groupName  }
    if(params.deviceName) newParams.device_name = { [Op.eq]: params.deviceName  }
    if(params.deviceVersion) newParams.device_version = { [Op.eq]: params.deviceVersion  }

    ctx.state.queryParam = newParams
    await next()
  } catch (error) {
    console.error('查询列表失败', error)
    return ctx.app.emit('error', getListErr, ctx)
  }
}
export const shebeiqueryConditionsDataFn = async (params:any) => {
  try {  
    const {groupName} = params
    const whereOpt = {
      group_name:groupName
    };
    const res = await ShebeiTable2.findAll({
      raw: true, // 设置为 true，即可返回源数据
      where:whereOpt,
    });
    return res ? res : [];    
  } catch (error) {
    console.log(error)
  }
}
// 新增
export const getAddMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const { userName } = ctx.state.user as userType
    const addContent = ctx.request['body'] as Ishebei
    const addContent2 = { ...addContent, createBy: userName }
    const newAddContent = formatHumpLineTransfer(addContent2, 'line') as  IshebeiSer
    if (await isDuplicate(newAddContent)) {
      return ctx.app.emit('error', {code:'500',message:'新增失败,设备名称重复'}, ctx)
    }
    await addSer<IshebeiSer>(ShebeiTable2, newAddContent)
    await next()
  } catch (error) {
    console.error('新增失败', error)
    return ctx.app.emit('error', uploadParamsErr, ctx)
  }
}

// 删除
export const delMid = async (ctx: Context, next: () => Promise<void>) => {
  try {

    await delSer(ShebeiTable2, { table_id: ctx.state.ids })
  } catch (error) {
    console.error('删除失败', error)
    return ctx.app.emit('error', delErr, ctx)
  }

  await next()
}

// 获取详细数据
export const getDetailMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const res = await getDetailSer<IshebeiSer>(ShebeiTable2, { table_id: ctx.state.ids  })

    ctx.state.formatData = res
  } catch (error) {
    console.error('详细数据查询错误', error)
    return ctx.app.emit('error', sqlErr, ctx)
  }

  await next()
}

// 修改
export const putMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const { userName } = ctx.state.user as userType
    const res = ctx.request['body'] as Ishebei
    const lineData =  formatHumpLineTransfer(res, 'line') as IshebeiSer
    const { table_id} = lineData

    await putSer<IshebeiSer>(ShebeiTable2, { table_id}, { ...lineData, update_by: userName })

    await next()
  } catch (error) {
    console.error('修改失败', error)
    return ctx.app.emit('error', uploadParamsErr, ctx)
  }
}

// 导出
export const exportMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const list = ctx.state.formatData
    const dicts = ctx.state.dicts
    list.forEach((item:any,index) => {
      item.index = index + 1
    })
    // 表格数据
    const buffer = await excelJsExport({
      sheetName: '设备表',
      style: excelBaseStyle,
      headerColumns: [{"title":"序号","dataIndex":"index",width:300},{"title":"所属组名","dataIndex":"group_name",width:300},{"title":"设备名称","dataIndex":"device_name",width:300},{"title":"设备版本","dataIndex":"device_version",width:300}],
      tableData: list,
      dicts: dicts
    })
    ctx.state.buffer = buffer
    await next()
  } catch (error) {
    console.error('导出失败', error)
    return ctx.app.emit('error', exportExcelErr, ctx)
  }
}

// 对同一类型的设配参数key进行判重
export const isDuplicate = async (lineData) => {
  try {
    const {device_name} = lineData
    const whereOpt = {device_name};
    // 查找是否重复
    const res = (await ShebeiTable2.findOne({
      attributes: ['device_name'],
      where: whereOpt,
    })) as any;
    return res ? res.dataValues : null;    
  } catch (error) {
    console.log(error)
  }
}